#include <err.h>
#include <fts.h>
#include <stdio.h>
#include <string.h>
#include "FileUtils.hxx"

//static int      ptree(char * const argv[]);

/*
int main(int argc, char * const argv[])
{
    int rc;

    std::vector<std::string> files;

    if ((rc = ListFiles(argv[1],"cxx", files)) != 0)
        rc = 1;

    return rc;
}
*/

int ListFiles(char* dir, const char* ext, std::vector<std::string>& fileList)
{
    FTS *ftsp;
    FTSENT *p, *chp;

    //int fts_options = FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR;
    int fts_options = FTS_COMFOLLOW | FTS_LOGICAL;
    int rval = 0;

    char *filePath[2];
    filePath[0]=dir;
    filePath[1]=NULL;

    if ((ftsp = fts_open(filePath, fts_options, NULL)) == NULL)
    {
        warn("fts_open");
        return -1;
    }


    /* Initialize ftsp with as many argv[] parts as possible. */
    chp = fts_children(ftsp, 0);
    if (chp == NULL) 
    {
        return 0;               /* no files to traverse */
    }

    while ((p = fts_read(ftsp)) != NULL) 
    {
        switch (p->fts_info) 
        {
            case FTS_D:
                //printf("d %s\n", p->fts_path);
                 break;
            case FTS_F:
                if(strlen(p->fts_path)>5)
                {
                    int pathLen = strlen(p->fts_path);
                    int extLen = strlen(ext);
                    char* extptr = strstr(p->fts_path,ext);

                    if( extptr && (extptr - p->fts_path == pathLen - extLen))
                       	fileList.push_back(std::string(p->fts_path, pathLen));
                }
                break;
             default:
                 break;
          }
    }

    fts_close(ftsp);
    return 0;
}
